package com.example.socket.client;

import com.example.socket.core.Request;
import com.example.socket.core.Response;
import com.example.socket.exception.SocketException;
import com.example.socket.filter.session.ProxyInvokerSupport;
import org.slf4j.helpers.MessageFormatter;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

/**
 * @author frank
 * @param <T>
 */
public class SendProxyInvoker<T> extends ProxyInvokerSupport<T> implements
        InvocationHandler {

    /** 消息分发器 */
    private Client client;
    private int timeout;

    SendProxyInvoker(Client client, int timeout) {
        this.client = client;
        this.timeout = timeout;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        Request<Object> request = buildRequest(method, args);
        if (logger.isDebugEnabled()) {
            logger.debug("开始发送请求[{}] - SN[{}] ...", request.getCommand(),
                    request.getSn());
        }
        SocketFuture<?> future = client.send(request, true);
        Response<?> resp = (Response<?>) future.get(timeout, TimeUnit.MILLISECONDS);
        if (logger.isDebugEnabled()) {
            logger.debug("接受请求[{}]回应  - SN[{}] ...", resp.getCommand(),
                    resp.getSn());
        }

        if (resp.hasError()) {
            String msg = MessageFormatter.format("消息请求[{}]回应异常 - SN[{}]",
                    resp.getState(), resp.getSn()).getMessage();
            throw new SocketException(msg);
        }
        return resp.getBody();
    }

}
